#coding:utf-8
import pyTTS
import time
import os
import threading

class waveThread(threading.Thread):
    mainThread = None
    def __init__(self , main):
        threading.Thread.__init__(self)
        self.mainThread = main
    def run(self):
        self.mainThread.toWavListPro()
        
        
class speek():
    wavList = None
    def __init__(self , show , mainThread):
        #wx.Frame.__init__(self, None, -1, '语音朗读', size=wx.Size(420, 300))

    #create the button
        
        #self.seg = SEG()
        print u"初始化播放器"
        self.show = show
        self.mainThread = mainThread
        
        self.tts = pyTTS.Create()
        print self.tts.GetVoiceNames()
        #[u'MSMike', u'MSMary', u'MSSam', u'SampleTTSVoice', u'MSSimplifiedChineseVoice']
        self.prePresent = 0
        self.startTime = 0
        self.preWord = 0
        
        #self.tts.SetVoiceByName('MSSimplifiedChineseVoice')
        #self.tts.SetVoiceByName('VW Lily')
        self.tts.SetVoiceByName('MS-Lili-2052-20-DSK')
        self.tts.OnBookmark = self.OnBookmark
        self.tts.OnWord = self.OnWordSentence
        self.tts.OnSentence = self.OnWordSentence
        #self.tts.OnStartStream  = self.OnStartStream
        #self.tts.OnAnyEvent=self.OnStartStream
        
        
    #加载文件
    def loadFile(self , fileName):
        self.fileName = fileName.decode('utf-8', 'ignore')
        print "加载文件：" , self.fileName
        result = "".join(open(self.fileName).readlines()).decode('utf-8', 'ignore')
        self.wordsLength = float(len(result))
        print u"文件总长度：" , self.wordsLength
        if self.mainThread != None:
            self.mainThread.showFile(result)
        return result
    #分词
    def cut(self , text):
        wlist = self.seg.cut(text)
        wlist.reverse()
        return wlist
    
    def read(self , fileName):
        #fileName = "d:/设计模式_20091017.txt"
        #wx.MessageBox("1", "test", wx.ICON_QUESTION)
        text = self.loadFile(fileName)
        #wx.MessageBox("2", "test", wx.ICON_QUESTION)
        #text = ",".join(self.cut(text))
        #print text
        #file = open("")
        if self.show == None:
            self.tts.Speak(text)
        else:
            #self.tts.Speak(text)
            self.tts.Speak(text , pyTTS.tts_is_xml, pyTTS.tts_async)
            
    def readText(self , text):  
        length = len(text)
        self.startTime = 0
        if  length == 0:
            return
        self.wordsLength = float(length)
        #print len(text)
        if length > 100:
            #self.tts.Speak(u"全文"+ str(length) + u"字")
            pass
        if length > 2000:
            text = text[:2000]
        print "read" , length
        if self.show == None:
            self.tts.Speak(text)
        else:
            #self.tts.Speak(text)
            self.tts.Speak(text , pyTTS.tts_is_xml, pyTTS.tts_default)
            
    def readList(self , list):
        for l in list:
            #print "read:" , l
            
                self.read(l)
            
    #转换
    def toWav(self , path):
        #base = "d:/22"
        files = []
        i = 1;
        
        if os.path.isdir(path):
            
            list = os.listdir(path)
            
            for file in list:
                if(os.path.basename(file).endswith("txt")):
                    files.append(file.decode("gbk" , "ignore"))
                    print file.decode("gbk" , "ignore")
        else:
            files.append(os.path.basename(path))
            path = os.path.dirname(path)
            
        for f in files:
            #print i , "/" , len(files)
            text = self.loadFile(os.path.join(path , f))
            self.toWavCore(text ,  "转换文件：" + f +"," + str(i) + "/" +  str(len(files)))
            i = i + 1
            
    def toWavList(self , list):
        self.wavList = list
        #threading.Thread(None , self.toWavListPro).start()
        #import waveThread
        #wT = waveThread(self)
        self.toWavListPro()
        
    def toWavListPro(self):
        list = self.wavList
        print list
        #path = os.path.dirname(list[0])
        s1 = time.time()
        i = 1
        for f in list:
            #print i , "/" , len(files)
            text = self.loadFile(f)
            #print text
            self.fileName = f
            self.toWavCore(text ,  str(i) + "/" + str(len(list))+"转换文件：" + f )
            i = i + 1
        if self.mainThread != None:
            self.mainThread.info(u"转换完成 ,耗时"  + self.cal(int(time.time() - s1)))
            
    def toWavText(self , text):
        #self.fileName
        self.toWavCore(text ,  "转换文件：")
            
    #转换成wav
    def toWavCore(self , text , title):
        if len(text) == 0:
            return
        start = time.time()
        print "开始转换:" , self.fileName
        wavFile = os.path.join(os.path.dirname(self.fileName) , os.path.basename(self.fileName).replace("txt" , "wav"))
        #wavFile = wavFile
        if self.show  != None:
            self.show( (title + "转换开始，大约需要:").encode("utf-8" , "ignore") + self.cal(int(self.wordsLength *   0.00632)))
        print wavFile.encode("utf-8" , "ignore") , len(text)
        self.tts.SpeakToWave(wavFile.encode("utf-8" , "ignore") , text)
        #self.tts.SpeakToMemory(text)
        #output = self.tts.SpeakToMemory(self, text)
        
        #params = {'id': acodec.getCodecID('mp3'), 'bitrate': 128000, 'sample_rate': 44100, 'ext': 'mp3', 'channels': 2}

        #stream = self.tts.SpeakToMemory(text)
        #format = stream.Format.GetWaveFormatEx()
        #print stream.GetData()
        
        #f = open("d:/1.test.mp3" ,"w")
        #for l in stream.GetData():
         #   f.write(l)
        #f.close()
        #help(format)
        #print stream
#        temp = None
#        try:
#            while True:
#                temp = stream.next()
#                if temp == None:
#                    break
#                print temp
#        except:
#            print temp

        print u"写入" , wavFile , ",耗时：" , (time.time() - start) , ",平均速度：" , ( (time.time() - start) /self.wordsLength ) , "秒/每字"
        
    #暂停
    def pause(self ,  t = None):
        print u"暂停"
        self.tts.Pause()

    #继续
    def resume(self ,  t = None):
        print u"继续"
        self.tts.Resume()
        
    #停止
    def stop(self , t = None):
        print u"停止"
        self.tts.Stop()

    def cal(self , t):
        if t <= 0:
            return ""
        else:
            result = []
            if t >= 86400:
                d = t / 86400
                t = t % 86400
                result.append(str(d) + "天")
                
            if t >= 3600:
                h = t / 3600
                t = t % 3600
                result.append(str(h) + "小时")
            elif len(result) > 0:
                result.append("0小时")
            if t >= 60:
                m = t / 60
                t = t % 60
                result.append(str(m) + "分")
            result.append(str(t) + "秒")
            return "".join(result)
    def isSpeeking(self):
        return self.tts.IsSpeaking()
  #when the button is pressed, speak the current time with a bookmark in it
    def stopRead(self):
        #p=()
        #threading._start_new_thread(self.tts.Stop , p)
        self.tts.Skip(num_items = 100)

    def OnSpeak(self, event):
        print "speak"

  #print when the bookmark is encountered
    def OnBookmark(self, event):
        print "bookmark"

  #print whenever a word or sentence boundary is encountered
    def OnWordSentence(self, event):
        #print "word" , event.CharacterPosition 
        if event.CharacterPosition > 0:
            self.mainThread.showPoi(event.CharacterPosition , event.CharacterPosition + event.Length)
        #print "[present=" , self.prePresent , ",time=" , self.preTime , "]"  
        prePresent = self.prePresent
        
        if self.startTime == 0:
            self.startTime = time.time()
           
        curTime = time.time()
        result = ""
        #print "-------------------" + unicode(event.CharacterPosition)
        if event.CharacterPosition <= 0:
            result = "剩余时间：未知" 
        else:
            try:
                s = (event.CharacterPosition) / (curTime - self.startTime)
                #print u"速度" , str(s) , "l=" , str(event.CharacterPosition) , "t=" ,str(curTime - self.startTime)
                t = int((int(self.wordsLength) - event.CharacterPosition) / s)
                #print u"长度=" , (self.wordsLength - event.CharacterPosition) , u"速度=" , s , "t=" ,t
                curPresent = event.CharacterPosition / self.wordsLength
                #print event.CharacterPosition , self.wordsLength , curPresent
                result =  u"已完成：" + str(curPresent * 100)[:5] + "%," + u"剩余时间：" + self.cal(t) 
                #print result
            except Exception ,e:
                
                print e
            
        #result = "已完成：" + str(curPresent * 100)[:5] + "%," + "剩余时间：" + str(int((1 - (curPresent - self.prePresent))/((curPresent - self.prePresent)/(curTime - self.startTime))))
        #print result
        self.preWord = event.CharacterPosition
        #self.startTime = curTime
        #self.preTime = curTime
        self.show(result.decode('utf-8', 'ignore'))

    def OnStartStream(self , t=None , w=None):
        print "11"
    
if __name__ == '__main__':
    
#    s = speek(None , None)
#    s.readText(u"测试")
    print "231111"[:2]
    #tts.SpeakToWave("D:/3/test.mp3", u"测试出")
    #tts.SpeakToWave(u"d:/3/test.mp3" , u"d:/3/test.txt")
    #s.tts.SpeakToWave(fileName[0].encode("utf-8" , "ignore") , "11111111")
    #print s.loadFile("D:\\workspace\\text\\src\\text.py")
    
  


